package com.intelligence.pda.ui.scanlibrary;

import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;

import com.intelligence.androidlibrary.rxjava.RxBus;
import com.intelligence.androidlibrary.utils.SharePreferenceUtils;
import com.intelligence.androidlibrary.zxing.android.CaptureActivity;
import com.intelligence.pda.R;
import com.intelligence.pda.event.PendingEvent;
import com.intelligence.pda.parameter.OutstockDetailParameter;
import com.intelligence.pda.parameter.OutstockSaveParameter;
import com.intelligence.pda.retrofit.ApiCallback;
import com.intelligence.pda.ui.BaseActivity;
import com.intelligence.pda.ui.abnormal.AbnormalActivity;
import com.intelligence.pda.ui.scanlibrary.adapter.OutstockDetailAdapter;
import com.intelligence.pda.ui.scanlibrary.model.OutstockDetailModel;
import com.intelligence.pda.ui.signout.model.LoginOutModel;
import com.intelligence.pda.utils.AppConstants;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class DetailsActivity extends BaseActivity implements View.OnClickListener {
    @Bind(R.id.tv_toolbar_title)
    TextView tv_toolbar_title;
    @Bind(R.id.ll_toolbar_return)
    LinearLayout ll_toolbar_return;
    @Bind(R.id.et_scan)
    EditText et_scan;
    @Bind(R.id.tv_Enregistrer)
    TextView tv_Enregistrer;
    @Bind(R.id.radioButton)
    RadioButton radioButton;
    @Bind(R.id.lv_scan)
    ListView lv_scan;
    @Bind(R.id.tv_determine)
    TextView tv_determine;
    private String orderNos;
    private List<OutstockDetailModel.DataBean> dataBeanList;
    private OutstockDetailAdapter outstockDetailAdapter;
    private boolean isselectall = false;
    private int KEYCODE_ENTER = 66;

    private static final String DECODED_CONTENT_KEY = "codedContent";
    private static final String DECODED_BITMAP_KEY = "codedBitmap";
    private static final int REQUEST_CODE_SCAN = 0x0000;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_details);
        tv_toolbar_title.setText("扫描出库");
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        Intent intent = getIntent();
        if (intent != null)
            orderNos = intent.getStringExtra(AppConstants.DETAILS);
        initView();
        listener();
        rxBusObservers();

    }

    private void initView() {
        AppConstants.FILTER = false;//初始化是过滤
        getoutstockList();
        dataBeanList = new ArrayList<>();
        outstockDetailAdapter = new OutstockDetailAdapter(mActivity);
        lv_scan.setAdapter(outstockDetailAdapter);

        lv_scan.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                final OutstockDetailModel.DataBean dataBean = dataBeanList.get(position);

                //输入件数
                TextView et_Nombre = (TextView) view.findViewById(R.id.et_Nombre);
                et_Nombre.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        getDialog(position);
                    }
                });
                //上报异常
                TextView tv_rapport_Anormal = (TextView) view.findViewById(R.id.tv_rapport_Anormal);
                tv_rapport_Anormal.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startActivity(new Intent(mActivity, AbnormalActivity.class)
                                .putExtra(AppConstants.ORDER_NO, dataBean.getOrderNo())
                                .putExtra(AppConstants.EXTNORDER_NO, dataBean.getExtnOrderNo()));
                    }
                });

            }
        });

        //扫描
        et_scan.requestFocus();
        et_scan.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int i, KeyEvent keyEvent) {
                if (i == KEYCODE_ENTER && keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
                    String scan = et_scan.getText().toString();
                    if (TextUtils.isEmpty(scan)) {
                        return false;
                    }
                    String state = getInterrogation(scan);
                    if (!"-1".equals(state)) {
                        final int po = Integer.valueOf(state);
                        getDialog(po);
                    }
                    return true;
                }
                return false;
            }
        });
        //过滤掉已扫描扫描
        radioButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isselectall) {
                    //不过滤
                    radioButton.setChecked(false);
                    isselectall = false;
                    AppConstants.FILTER = false;//初始化是过滤
                    outstockDetailAdapter.addData(dataBeanList);

                } else {
                    //过滤的
                    radioButton.setChecked(true);
                    isselectall = true;
                    AppConstants.FILTER = true;//初始化是过滤
                    outstockDetailAdapter.addData(dataBeanList);
                }
            }
        });
    }

    private void listener() {
        ll_toolbar_return.setOnClickListener(this);
        tv_Enregistrer.setOnClickListener(this);
        tv_determine.setOnClickListener(this);
        et_scan.addTextChangedListener(new EditChangedListener());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_toolbar_return:
                if (dataNo()) {
                    getDataDialog();
                } else {
                    finish();
                }
                break;
            case R.id.tv_Enregistrer:
                if (tv_Enregistrer.getText().toString().equals("扫描")) {
                    Intent intent = new Intent(mActivity, CaptureActivity.class);
                    startActivityForResult(intent, REQUEST_CODE_SCAN);
                    return;

                }
                //保存
                String scan = et_scan.getText().toString();
                if (TextUtils.isEmpty(scan)) {
                    toastShow("请输入订单号");
                    return;
                }
                String state = getInterrogation(scan);
                if (!"-1".equals(state)) {
                    final int po = Integer.valueOf(state);
                    getDialog(po);
                }
                et_scan.setText("");
                et_scan.requestFocus();//获取焦点 光标出现
                break;
            case R.id.tv_determine:
                //提交出库
                getoutstockSave();
                break;
        }

    }

    /**
     * 接口
     * 出库明细
     */
    public void getoutstockList() {
        //出库明细
        OutstockDetailParameter outstockDetailParameter = new OutstockDetailParameter();
        outstockDetailParameter.setOrderNos(orderNos);
        outstockDetailParameter.setBasicStr(SharePreferenceUtils.getString(AppConstants.BASIC_STR));
        addSubscription(apiStores.getoutstockDetail(outstockDetailParameter),
                new ApiCallback<OutstockDetailModel>() {
                    @Override
                    public void onSuccess(OutstockDetailModel model) {
                        dataBeanList.clear();
                        dataBeanList = model.getData();
                        outstockDetailAdapter.addData(dataBeanList);
                    }

                    @Override
                    public void onFailure(OutstockDetailModel model, String msg) {
                        toastShow(msg);
                    }

                    @Override
                    public void onFailure(String msg) {
                        toastShow(msg);
                    }


                    @Override
                    public void onFinish() {
                    }

                });


    }

    /**
     * 接口
     * 出库提交
     */
    public void getoutstockSave() {
        //出库提交
        OutstockSaveParameter outstockSaveParameter = new OutstockSaveParameter();
        List<OutstockSaveParameter.orderListBean> orderListBeanList = new ArrayList<>();
        for (int i = 0; i < dataBeanList.size(); i++) {
            if (dataBeanList.get(i).isOut()) {
                OutstockSaveParameter.orderListBean orderListBean = new OutstockSaveParameter.orderListBean();
                orderListBean.setOrderNo(dataBeanList.get(i).getOrderNo());
                orderListBean.setAmount(dataBeanList.get(i).getAmounts());
                orderListBeanList.add(orderListBean);
            }
        }
        if (dataBeanList.size() > 0) {
            outstockSaveParameter.setOrderList(orderListBeanList);
        } else {
            toastShow("没有提交扫描货物信息");
            return;
        }
        outstockSaveParameter.setBasicStr(SharePreferenceUtils.getString(AppConstants.BASIC_STR));
        showProgressDialog();
        addSubscription(apiStores.getoutstockSave(outstockSaveParameter),
                new ApiCallback<LoginOutModel>() {
                    @Override
                    public void onSuccess(LoginOutModel model) {
                        AppConstants.FILTER = false;//初始化是过滤
                        radioButton.setChecked(false);
                        toastShow("出库提交成功");
                        dismissProgressDialog();
                        finish();
                    }

                    @Override
                    public void onFailure(LoginOutModel model, String msg) {
                        toastShow(msg);
                        dismissProgressDialog();
                    }

                    @Override
                    public void onFailure(String msg) {
                        toastShow(msg);
                        dismissProgressDialog();
                    }


                    @Override
                    public void onFinish() {
                        dismissProgressDialog();
                    }

                });


    }

    /**
     * 查询功能
     * 查询是否有订单
     *
     * @orderNo
     */
    public String getInterrogation(String orderNo) {
        if (!TextUtils.isEmpty(orderNo)) {
            for (int i = 0; i < dataBeanList.size(); i++) {
                if (orderNo.equals(dataBeanList.get(i).getOrderNo())) {
                    if (dataBeanList.get(i).isOut()) {
                        et_scan.setText("");
                        et_scan.requestFocus();//获取焦点 光标出现
                        getDataNO("已经扫描过订单");
                        return "-1";

                    } else {
                        dataBeanList.get(i).setOut(true);
                        toastShow("扫描成功");
                        outstockDetailAdapter.addData(dataBeanList);
                        return String.valueOf(i);
                    }

                }

            }
            et_scan.setText("");
            et_scan.requestFocus();//获取焦点 光标出现
            getDataNO("无此订单号");
            return "-1";
        }
        return "-1";
    }

    /**
     * 对话框Dialog
     * 输入笔数
     *
     * @position
     **/
    public void getDialog(final int position) {
        final OutstockDetailModel.DataBean dataBean = dataBeanList.get(position);
        final AlertDialog builder = new AlertDialog.Builder(mActivity).create();
        View views = LayoutInflater.from(mActivity).inflate(R.layout.dialog_custom_layout, null);
        builder.setView(views);
        TextView tvTitle = (TextView) views.findViewById(R.id.tv_title);
        final EditText edit_num = (EditText) views.findViewById(R.id.edit_num);
        Button btnPositive = (Button) views.findViewById(R.id.btn_positive);
        Button btnNegative = (Button) views.findViewById(R.id.btn_negative);
        tvTitle.setText("修改商品数量");
        edit_num.setText(dataBean.getAmount());
        edit_num.setSelection(edit_num.getText().toString().length());
        btnPositive.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                et_scan.setText("");
                et_scan.requestFocus();//获取焦点 光标出现
                dataBeanList.get(position).setAmounts(String.valueOf(1));
                outstockDetailAdapter.addData(dataBeanList);
                builder.dismiss();
            }
        });
        btnNegative.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int num_nistory = Integer.valueOf(dataBean.getAmount());//历史数量
                int num_new = Integer.valueOf(edit_num.getText().toString());//输入数量
                if (num_new > 0) {
                    if (num_nistory >= num_new) {

                        et_scan.setText("");
                        et_scan.requestFocus();//获取焦点 光标出现

                        dataBeanList.get(position).setAmounts(String.valueOf(num_new));
                        outstockDetailAdapter.addData(dataBeanList);
                        builder.dismiss();

                    } else {
                        toastShow("最大数量不能超过" + num_nistory + "笔");
                    }
                } else {
                    toastShow("最小数量不能小于1笔");
                }

            }
        });
        builder.show();
    }

    /**
     * 对话框Dialog
     *
     * @position
     **/
    public void getDataDialog() {
        final AlertDialog builder = new AlertDialog.Builder(mActivity).create();
        View views = LayoutInflater.from(mActivity).inflate(R.layout.dialog_layout, null);
        builder.setView(views);
        TextView tvTitle = (TextView) views.findViewById(R.id.tv_title);
        TextView tv_tv_Prompt = (TextView) views.findViewById(R.id.tv_Prompt);
        Button btnPositive = (Button) views.findViewById(R.id.btn_positive);
        Button btnNegative = (Button) views.findViewById(R.id.btn_negative);
        tvTitle.setText("提示");
        tv_tv_Prompt.setText("退出数据将会清除,是否继续");
        btnPositive.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //取消
                builder.dismiss();
            }
        });
        btnNegative.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //确定
                finish();
                builder.dismiss();

            }
        });
        builder.show();
    }

    /**
     * 是否存在未提交数据
     **/

    public boolean dataNo() {
        for (int i = 0; i < dataBeanList.size(); i++) {
            if (dataBeanList.get(i).isOut()) {
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (dataNo()) {
                    getDataDialog();
                } else {
                    finish();
                }
                break;
        }
        return false;
    }

    //手机扫描返回
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 扫描二维码/条码回传
        if (requestCode == REQUEST_CODE_SCAN && resultCode == RESULT_OK) {
            if (data != null) {
                String content = data.getStringExtra(DECODED_CONTENT_KEY);
                Bitmap bitmap = data.getParcelableExtra(DECODED_BITMAP_KEY);
                String state = getInterrogation(content);
                if (!"-1".equals(state)) {
                    final int po = Integer.valueOf(state);
                    getDialog(po);
                }

            }
        }
    }

    class EditChangedListener implements TextWatcher {
        private CharSequence temp = "";//监听前的文本
        private int editStart;//光标开始位置
        private int editEnd;//光标结束位置
        private final int charMaxNum = 10;
        String TAG = "测试：";

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            Log.i(TAG, "输入文本之前的状态");
            temp = s;
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            Log.i(TAG, "输入文字中的状态，count是一次性输入字符数");


        }

        @Override
        public void afterTextChanged(Editable s) {
            Log.i(TAG, "输入文字后的状态");
            try {
                if (temp.length() == 0) {
                    tv_Enregistrer.setText("扫描");
                } else {
                    tv_Enregistrer.setText("保存");
                }
            } catch (Exception ex) {

            }

        }

    }

    /**
     * 对话框Dialog
     *
     * @position
     **/
    public void getDataNO(String text) {
        final AlertDialog builder = new AlertDialog.Builder(mActivity).create();
        View views = LayoutInflater.from(mActivity).inflate(R.layout.dialog_layout2, null);
        builder.setView(views);
        TextView tvTitle = (TextView) views.findViewById(R.id.tv_title);
        TextView tv_tv_Prompt = (TextView) views.findViewById(R.id.tv_Prompt);

        Button btnNegative = (Button) views.findViewById(R.id.btn_negative);
        tvTitle.setText("提示");
        tv_tv_Prompt.setText(text);
        btnNegative.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //确定
                et_scan.setText("");
                et_scan.requestFocus();//获取焦点 光标出现
                builder.dismiss();

            }
        });
        builder.show();
    }

    /**
     * @Rxjava
     * @用于布局，通知更新
     **/
    private void rxBusObservers() {
        //接受事件
        addSubscription(RxBus.getInstance()
                .toObserverable()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<Object>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(Object event) {
                        if (event instanceof PendingEvent) {
                            //是否有事件
                            String orderNo=((PendingEvent) event).getOrderNo();
                            if (!TextUtils.isEmpty(orderNo)) {
                                for (int i = 0; i < dataBeanList.size(); i++) {
                                    if (orderNo.equals(dataBeanList.get(i).getOrderNo())){
                                        dataBeanList.get(i).setButton(false);
                                        outstockDetailAdapter.addData(dataBeanList);

                                    }

                                }
                            }

                        }
                    }
                }));
    }

}
